package net.huashitong.commCtrl;

import com.alibaba.fastjson.JSONArray;
import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysFile;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.service.SysFileService;
import net.huashitong.Project.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


/**
 * 公用类。
 * 工用的上传 下载，
 */

@Controller
@RequestMapping("/communal")
public class CommCtrl  extends JsonBaseController {

    @Autowired
    private SysFileService fileservice;



    @Override
    protected String getView(String s) {
        return null;
    }

    //文件上传
    @ResponseBody
    @RequestMapping("/uploadBatch")
    public String uplaodfile(@RequestParam MultipartFile files) {
        String str = null;
        Message msg = new Message();
        if (files == null) {
            msg.setCode("500");
            return null;
        }
        //System.out.println(projectStage);
        Map<String, Object> mao = new HashMap<String, Object>();

        try {

            SysFile sysfile = new SysFile();

            fileservice.saveFile(sysfile, files);
            //filesave.fileSave(sysfile, files);

            mao.put("sysid", sysfile.getSysId());


            msg.setCode("200");
            msg.setData(mao);
            str = JSONArray.toJSONString(msg);



        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;
    }

    //文件下载
    @RequestMapping(value = "/download/{id}")
    public void downLoad(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downLoadFileId(id, req, resp);
    }


    public void downLoadFileId(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        SysFile sysFile = fileservice.getById(fileId);
        if (sysFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        resp.reset();
        InputStream inputStream =new FileInputStream(file);
        try {


            resp.setHeader("Content-Type", "application/x-download");
            resp.setHeader("Content-Disposition", "attachment; filename=" +sysFile.getFilename() + "." + sysFile.getFileType()  );
            FileCopyUtils.copy(inputStream, resp.getOutputStream());


            return ;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }


    }

}
